package com.lanxin.zc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.Page;
import com.lanxin.bx.entity.BxInformal;
import com.lanxin.bx.entity.BxInformalaccessary;
import com.lanxin.bx.entity.BxInformaldetail;
import com.lanxin.bx.entity.BxInformaltype;
import com.lanxin.bx.vo.AllinformalVo;
import com.lanxin.hr.entity.ZzAccount;
import com.lanxin.hr.entity.ZzDepartment;
import com.lanxin.hr.entity.ZzEmployee;
import com.lanxin.hr.service.IZzAccountService;
import com.lanxin.hr.service.IZzDepartmentService;
import com.lanxin.hr.service.IZzEmployeeService;
import com.lanxin.judge.Vo.NodeVo;
import com.lanxin.judge.entity.LcApproval;
import com.lanxin.judge.entity.LcFlow;
import com.lanxin.judge.service.ILcApprovalService;
import com.lanxin.judge.service.ILcFlowService;
import com.lanxin.judge.service.ILcNodeService;
import com.lanxin.zc.entity.ZcAssetbaojia;
import com.lanxin.zc.entity.ZcAssetpurchaseapply;
import com.lanxin.zc.entity.ZcAssetpurchaseapplydetails;
import com.lanxin.zc.service.IZcAssetbaojiaService;
import com.lanxin.zc.service.IZcAssetpurchaseapplyService;
import com.lanxin.zc.service.IZcAssetpurchaseapplydetailsService;
import com.lanxin.zc.vo.AllzcassetpurchaseapplyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2025-07-16
 */
@Controller
@RequestMapping("/zc-assetpurchaseapply")
public class ZcAssetpurchaseapplyController {

    @Autowired
    private IZcAssetpurchaseapplyService zcAssetpurchaseapplyService;
    @Autowired
    private IZzEmployeeService zzEmployeeService;
    @Autowired
    private IZzDepartmentService zzDepartmentService;
    @Autowired
    private IZcAssetpurchaseapplydetailsService zzAssetpurchaseapplydetailsService;
    @Autowired
    private ILcFlowService lcFlowService;
    @Autowired
    private IZzAccountService zzAccountService;
    @Autowired
    private IZcAssetbaojiaService zzAssetbaojiaService;
    @Autowired
    private ILcApprovalService lcApprovalService;
    @Autowired
    private ILcNodeService lcNodeService;

    @RequestMapping("/toallzcassetpurchaseapplylist")
    public ModelAndView toallzcassetpurchaseapplylist(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "docNo", required = false) String docNo,
            @RequestParam(value = "empName", required = false) String empName,
            @RequestParam(value = "submitDate", required = false) String submitDate,
            @RequestParam(value = "status", required = false) String status) {

        // 调用服务层获取分页数据
        Page<AllzcassetpurchaseapplyVo> allzcassetpurchaseapplyVoPage = zcAssetpurchaseapplyService.selectzcassetpurchList(page, pageSize, docNo, empName, submitDate, status);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("zc/zcassetpurchaseapply/allzcassetpurchaseapplylist");

        // 添加分页数据到视图
        modelAndView.addObject("allzcassetpurchaseapplyVoPage", allzcassetpurchaseapplyVoPage);
        modelAndView.addObject("docNo", docNo);
        modelAndView.addObject("empName", empName);
        modelAndView.addObject("submitDate", submitDate);
        modelAndView.addObject("status", status);

        // 添加分页信息（可选）
        modelAndView.addObject("total", allzcassetpurchaseapplyVoPage.getTotal());
        modelAndView.addObject("pageNum", allzcassetpurchaseapplyVoPage.getPageNum());
        modelAndView.addObject("pageSize", allzcassetpurchaseapplyVoPage.getPageSize());
        modelAndView.addObject("pages", allzcassetpurchaseapplyVoPage.getPages()); // 总页数

        return modelAndView;
    }

    @RequestMapping("/tomyallzcassetpurchaseapplylist")
    public ModelAndView tomyallzcassetpurchaseapplylist(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "docNo", required = false) String docNo,
            @RequestParam(value = "submitDate", required = false) String submitDate,
            @RequestParam(value = "status", required = false) String status, HttpSession session) {

        // 调用服务层获取分页数据
        ZzAccount myaccount = (ZzAccount) session.getAttribute("myaccount");
        QueryWrapper<ZzEmployee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid", myaccount.getAid());
        ZzEmployee employee= zzEmployeeService.getOne(queryWrapper);
        Page<AllzcassetpurchaseapplyVo> allzcassetpurchaseapplyVoPage = zcAssetpurchaseapplyService.selectmyzcassetpurchList(page, pageSize, docNo,  submitDate, status,employee.getOid());

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("zc/zcassetpurchaseapply/myallzcassetpurchaseapplylist");

        // 添加分页数据到视图
        modelAndView.addObject("allzcassetpurchaseapplyVoPage", allzcassetpurchaseapplyVoPage);
        modelAndView.addObject("docNo", docNo);
        modelAndView.addObject("submitDate", submitDate);
        modelAndView.addObject("status", status);

        // 添加分页信息（可选）
        modelAndView.addObject("total", allzcassetpurchaseapplyVoPage.getTotal());
        modelAndView.addObject("pageNum", allzcassetpurchaseapplyVoPage.getPageNum());
        modelAndView.addObject("pageSize", allzcassetpurchaseapplyVoPage.getPageSize());
        modelAndView.addObject("pages", allzcassetpurchaseapplyVoPage.getPages()); // 总页数

        return modelAndView;
    }

    @RequestMapping("/subZcAssetpurchaseapply1")
    @ResponseBody
    public boolean subZcAssetpurchaseapply1(@RequestParam Integer oid){

        QueryWrapper<ZcAssetpurchaseapplydetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parentid",oid);
        long count = zzAssetpurchaseapplydetailsService.count(queryWrapper);
        if(count > 0){
            QueryWrapper<ZcAssetpurchaseapply> bxInformalQueryWrapper = new QueryWrapper<>();
            bxInformalQueryWrapper.eq("oid",oid);
            ZcAssetpurchaseapply zcAssetpurchaseapply=zcAssetpurchaseapplyService.getOne(bxInformalQueryWrapper);
            String state="B";
            zcAssetpurchaseapply.setStatus(state);
            zcAssetpurchaseapply.setSubmitDate(LocalDateTime.now());
            zcAssetpurchaseapplyService.updateById(zcAssetpurchaseapply);
            return true;
        }else {

            return false;

        }

    }

    @RequestMapping("/subZcAssetpurchaseapply2")
    @ResponseBody
    public boolean subZcAssetpurchaseapply2(@RequestParam Integer oid) {

        QueryWrapper<ZcAssetpurchaseapplydetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parentid", oid);
        List<ZcAssetpurchaseapplydetails> zcAssetpurchaseapplydetails = zzAssetpurchaseapplydetailsService.list(queryWrapper);
        boolean s = false;
        if (zcAssetpurchaseapplydetails != null && zcAssetpurchaseapplydetails.size() > 0) {
        for (int i = 0; i < zcAssetpurchaseapplydetails.size(); i++) {
            QueryWrapper<ZcAssetbaojia> baojiaQueryWrapper = new QueryWrapper<>();
            baojiaQueryWrapper.eq("parentid", zcAssetpurchaseapplydetails.get(i).getOid());
            long count = zzAssetbaojiaService.count(baojiaQueryWrapper);
            if (count > 0) {
                QueryWrapper<ZcAssetpurchaseapply> bxInformalQueryWrapper = new QueryWrapper<>();
                bxInformalQueryWrapper.eq("oid", oid);
                ZcAssetpurchaseapply zcAssetpurchaseapply = zcAssetpurchaseapplyService.getOne(bxInformalQueryWrapper);
                String state = "O";
                zcAssetpurchaseapply.setStatus(state);
                zcAssetpurchaseapply.setSubmitDate(LocalDateTime.now());
                zcAssetpurchaseapplyService.updateById(zcAssetpurchaseapply);
                s=true;
            } else {

                s = false;

            }

        }
        }
        return s;
    }

    @RequestMapping("/toeditZcAssetpurchaseapply")
    public ModelAndView toeditZcAssetpurchaseapply(@RequestParam(required = false) Integer oid) {
        ModelAndView modelAndView = new ModelAndView();

        // 查询流程列表
        QueryWrapper<LcFlow> LCqueryWrapper = new QueryWrapper<>();
        LCqueryWrapper.eq("state", "Y");
        LCqueryWrapper.eq("docType","GMD");
        List<LcFlow> lcFlow = lcFlowService.list(LCqueryWrapper);
        modelAndView.addObject("lcFlow", lcFlow);

        // 如果oid不为空，查询已有数据
        if (oid != null) {
            // 查询主表信息
            ZcAssetpurchaseapply apply = zcAssetpurchaseapplyService.getById(oid);
            if (apply != null) {
                modelAndView.addObject("zcAssetpurchaseapply", apply);

                // 查询申请人信息
                if (apply.getProposer() != null) {
                    ZzEmployee proposer = zzEmployeeService.getById(apply.getProposer());
                    if (proposer != null) {
                        modelAndView.addObject("empName", proposer.getEmpName());
                    }
                }

                // 查询明细信息
                QueryWrapper<ZcAssetpurchaseapplydetails> detailQuery = new QueryWrapper<>();
                detailQuery.eq("parentid", oid);
                List<ZcAssetpurchaseapplydetails> details = zzAssetpurchaseapplydetailsService.list(detailQuery);
                modelAndView.addObject("details", details);
            }
        }

        modelAndView.setViewName("zc/zcassetpurchaseapply/editZcAssetpurchaseapply");
        return modelAndView;
    }

    @RequestMapping("/editZcAssetpurchaseapply")
    public String editZcAssetpurchaseapply(
            @RequestParam(required = false) Integer oid,
            @RequestParam(value = "docNo", required = false) String docNo,
            @RequestParam(value = "flowid", required = false) Integer flowid,
            @RequestParam(value = "reason", required = false) String reason,
            @RequestParam(value = "remark", required = false) String remark,
            @RequestParam(value = "proposer", required = false) Integer proposer,
            @RequestParam(value = "empName", required = false) String empName,
            @RequestParam(value = "assetName", required = false) String[] assetNames,
            @RequestParam(value = "assetNumber", required = false) String[] assetNumbers,
            @RequestParam(value = "guige", required = false) String[] guiges,
            @RequestParam(value = "purchaseDate", required = false) String[] purchaseDates,
            @RequestParam(value = "unitPrice", required = false) BigDecimal[] unitPrices,
            @RequestParam(value = "quantity", required = false) Integer[] quantities,
            HttpSession session) {

        // 获取当前登录用户信息
        ZzAccount myaccount = (ZzAccount) session.getAttribute("myaccount");
        if (myaccount == null) {
            return "redirect:/login";
        }

        // 判断是新增还是修改
        boolean isUpdate = oid != null;

        // 获取或创建申请单对象
        ZcAssetpurchaseapply zcAssetpurchaseapply = isUpdate ?
                zcAssetpurchaseapplyService.getById(oid) : new ZcAssetpurchaseapply();

        if (zcAssetpurchaseapply == null) {
            // 如果要修改的记录不存在，按新增处理
            zcAssetpurchaseapply = new ZcAssetpurchaseapply();
            isUpdate = false;
        }

        // 设置基本属性
        zcAssetpurchaseapply.setOid(oid);
        zcAssetpurchaseapply.setFlowid(flowid);
        zcAssetpurchaseapply.setReason(reason);
        zcAssetpurchaseapply.setRemark(remark);

        // 设置创建者和申请者
        if (!isUpdate) {
            zcAssetpurchaseapply.setCreator(myaccount.getAid());
            zcAssetpurchaseapply.setCreateDate(LocalDateTime.now());
        }
        zcAssetpurchaseapply.setProposer(proposer);
        QueryWrapper<ZzEmployee> departmentQuery = new QueryWrapper<>();
        departmentQuery.eq("oid", proposer);
        ZzEmployee zzEmployee= zzEmployeeService.getOne(departmentQuery);
        if (proposer != null) {

            zcAssetpurchaseapply.setDeptid(zzEmployee.getDeptid());
        } else {
            zcAssetpurchaseapply.setProposer(myaccount.getAid());
            QueryWrapper<ZzEmployee> departmentQuery2 = new QueryWrapper<>();
            departmentQuery2.eq("oid", myaccount.getAid());
            ZzEmployee zzEmployee2= zzEmployeeService.getOne(departmentQuery);
            zcAssetpurchaseapply.setDeptid(zzEmployee2.getDeptid());
        }



        // 设置状态（新增时设置为"W"，修改时不改变原状态）
        if (!isUpdate) {
            zcAssetpurchaseapply.setStatus("W"); // 初始状态
        }

        // 生成申请单号（仅新增时生成）
        if (!isUpdate && (docNo == null || docNo.isEmpty())) {
            docNo = "GMD" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                    + String.format("%04d", (int)(Math.random() * 10000));
            zcAssetpurchaseapply.setDocNo(docNo);
            zcAssetpurchaseapply.setDoctype("GMD");
        }

        // 保存或更新主表信息
        zcAssetpurchaseapplyService.saveOrUpdate(zcAssetpurchaseapply);

        // 处理购买明细
        if (assetNames != null && assetNames.length > 0) {
            // 如果是修改，先删除旧的明细
            if (isUpdate) {
                QueryWrapper<ZcAssetpurchaseapplydetails> deleteWrapper = new QueryWrapper<>();
                deleteWrapper.eq("parentid", oid);
                zzAssetpurchaseapplydetailsService.remove(deleteWrapper);
            }

            List<ZcAssetpurchaseapplydetails> details = new ArrayList<>();

            for (int i = 0; i < assetNames.length; i++) {
                if (StringUtils.isEmpty(assetNames[i])) {
                    continue; // 跳过空明细
                }

                ZcAssetpurchaseapplydetails detail = new ZcAssetpurchaseapplydetails();
                detail.setParentid(zcAssetpurchaseapply.getOid());
                detail.setAssetName(assetNames[i]);
                detail.setAssetNumber(assetNumbers != null && i < assetNumbers.length ? assetNumbers[i] : null);
                detail.setGuige(guiges != null && i < guiges.length ? guiges[i] : null);

                // 处理日期转换
                if (purchaseDates != null && i < purchaseDates.length && !purchaseDates[i].isEmpty()) {
                    try {
                        detail.setPurchaseDate(LocalDate.parse(purchaseDates[i]));
                    } catch (DateTimeParseException e) {
                        // 日期格式错误处理
                        detail.setPurchaseDate(null);
                    }
                }

                detail.setUnitPrice(unitPrices != null && i < unitPrices.length ? unitPrices[i] : null);
                detail.setQuantity(quantities != null && i < quantities.length ? quantities[i] : null);

                details.add(detail);
            }

            // 保存明细列表
            if (!details.isEmpty()) {
                zzAssetpurchaseapplydetailsService.saveBatch(details);
            }
        }
        //5.添加审批单子
        LcApproval lcApproval = new LcApproval();
        lcApproval.setDoctype(zcAssetpurchaseapply.getDoctype());
        lcApproval.setDocNo(zcAssetpurchaseapply.getDocNo());
        lcApproval.setDocid(zcAssetpurchaseapply.getOid());
        lcApproval.setProposer(myaccount.getAid());
        lcApproval.setDeptid(zzEmployee.getDeptid());
        lcApproval.setFlowid(zcAssetpurchaseapply.getFlowid());
        List<NodeVo> lcNodes=lcNodeService.listNode(zcAssetpurchaseapply.getFlowid());
        lcApproval.setNodeid(lcNodes.get(0).getOid());
        lcApproval.setStatus("O");
        lcApproval.setSubmitDate(LocalDateTime.now());
        lcApprovalService.save(lcApproval);

        return "redirect:/zc-assetpurchaseapply/tomyallzcassetpurchaseapplylist";
    }

    @RequestMapping("/toBaojia")
    public ModelAndView toBaojia(@RequestParam(required = false) Integer oid) {
        ModelAndView modelAndView = new ModelAndView();
        QueryWrapper<ZcAssetpurchaseapplydetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parentid", oid);
        List<ZcAssetpurchaseapplydetails> details = zzAssetpurchaseapplydetailsService.list(queryWrapper);
        modelAndView.addObject("details", details);
        modelAndView.addObject("oid", oid);
        modelAndView.setViewName("zc/zcassetpurchaseapply/tobaojia");
        return modelAndView;
    }

    @RequestMapping("/addBaojia")
    @Transactional
    public String addBaojia(@RequestParam Integer oid,
                            @RequestParam(value = "detailIds", required = false) List<Integer> detailIds,
                            @RequestParam(value = "prices", required = false) List<BigDecimal> prices,
                            @RequestParam(value = "linkmans", required = false) List<String> linkmans,
                            @RequestParam(value = "linkPhones", required = false) List<String> linkPhones,
                            @RequestParam(value = "remarks", required = false) List<String> remarks) {

        if(detailIds == null || detailIds.isEmpty() ||
                prices == null || prices.isEmpty() ||
                linkmans == null || linkmans.isEmpty() ||
                linkPhones == null || linkPhones.isEmpty()) {
            return "redirect:/zc-assetpurchaseapply/tomyallzcassetpurchaseapplylist";
        }

        for(int i = 0; i < detailIds.size(); i++) {
            // 检查明细是否存在
            ZcAssetpurchaseapplydetails detail = zzAssetpurchaseapplydetailsService.getById(detailIds.get(i));
            if(detail == null) {
                throw new RuntimeException("明细不存在，ID: " + detailIds.get(i));
            }

            ZcAssetbaojia baojia = new ZcAssetbaojia();
            baojia.setParentid(detailIds.get(i)); // 主表ID
            baojia.setPrice(prices.get(i));
            baojia.setLinkman(linkmans.get(i));
            baojia.setLinkPhone(linkPhones.get(i));
            baojia.setRemark(remarks.get(i));

            zzAssetbaojiaService.save(baojia);
        }

        return "redirect:/zc-assetpurchaseapply/tomyallzcassetpurchaseapplylist";
    }

    @RequestMapping("/deleteAssetpurchaseapply")
    @ResponseBody
    @Transactional
    public boolean deleteAssetpurchaseapply(@RequestParam Integer oid) {
        // 1. 先删除所有报价信息（三级关联数据）
        QueryWrapper<ZcAssetpurchaseapplydetails> detailsQuery = new QueryWrapper<>();
        detailsQuery.eq("parentid", oid);
        List<ZcAssetpurchaseapplydetails> detailsList = zzAssetpurchaseapplydetailsService.list(detailsQuery);

        for (ZcAssetpurchaseapplydetails detail : detailsList) {
            // 删除每个明细项关联的报价信息
            QueryWrapper<ZcAssetbaojia> baojiaQuery = new QueryWrapper<>();
            baojiaQuery.eq("parentid", detail.getOid());
            zzAssetbaojiaService.remove(baojiaQuery);
        }

        // 2. 删除采购申请明细（二级关联数据）
        zzAssetpurchaseapplydetailsService.remove(detailsQuery);

        // 3. 最后删除主表数据
        return zcAssetpurchaseapplyService.removeById(oid);
    }


}
